import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/match/req_match.dart';
import 'package:flutter_changdian_football/routers/app_routes.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:tobias/tobias.dart' as tobias;

class RechargePaymentController extends GetxController {
  static RechargePaymentController get to => Get.find();

  RechargePaymentController({
    required this.matchId
  });

  final String matchId;

  @override
  void onInit() {
    super.onInit();

    matchSinUpFee();
  }

  String? userId;
  String userBalance = '0.00';
  String venueFees = '0.00';

  // 支付方式
  String payType = '0';
  changePayType(p) {
    payType = p;
    update();
  }

  // 获取比赛场地费和用户余额
  matchSinUpFee() async {
    try {
      EasyLoading.show();

      var resp = await ReqMatch.matchSinUpFee(
        matchId: matchId
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          userId = '${resp.data['data']['userId']}';
          userBalance = double.parse('${resp.data['data']['userBalance'] ?? '0.00'}').toStringAsFixed(2);
          venueFees = double.parse('${resp.data['data']['venueFees'] ?? '0.00'}').toStringAsFixed(2);
          update();
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      logger.d(e);
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }




  // 0-支付中 1-支付成功  2-支付失败
  int payResult = 0;
  String title = '';
  String desc = '';

  payment() async {
    if (userId == null) {
      return ;
    }
    if (payType == '0') {
      if (double.parse('${userBalance}') < double.parse('${venueFees}')) {
        CustomToast.showTextToast('余额不足');
        return ;
      }
    }

    try {
      EasyLoading.show();

      var resp = await ReqMatch.paySignUpFee(
        matchId: matchId,
        payAmount: venueFees,
        paymentMethod: payType == '0' ? 'BALANCE' : 'ZFB'
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          if (payType == '0') {
            Get.offNamed(AppRoutes.payResult, parameters: {
              'orderNo': '',
              'venueFees': '${double.parse('$venueFees').toStringAsFixed(2)}',
              'payType': '${payType}',
              'payResult': '1',
              'desc': '支付成功'
            });
          } else {
            toAliPay(resp.data['data']);
          }
        } else {
          Get.offNamed(AppRoutes.payResult, parameters: {
            'orderNo': '',
            'venueFees': '${double.parse('$venueFees').toStringAsFixed(2)}',
            'payType': '${payType}',
            'payResult': '2',
            'desc': resp.data['msg']
          });
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
        update();
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
      update();
    } finally {
      EasyLoading.dismiss();
      
    }
  }


  toAliPay(payInfo) async {
    var result = await tobias.isAliPayInstalled();
    if (result) {
      tobias.aliPay(payInfo).then((value) {
        if (int.parse(value['resultStatus']) == 9000) {
          title = '支付成功';
          payResult = 1;
          update();
        } else if (int.parse(value['resultStatus']) == 8000) {
          title = '支付成功';
          payResult = 1;
          update();
        } else if (int.parse(value['resultStatus']) == 4000) {
          Get.offNamed(AppRoutes.payResult, parameters: {
            'orderNo': '',
            'venueFees': '${double.parse('$venueFees').toStringAsFixed(2)}',
            'payType': '${payType}',
            'payResult': '2',
            'desc': '订单支付失败，请稍后再试'
          });
        } else if (int.parse(value['resultStatus']) == 6001) {
          Get.offNamed(AppRoutes.payResult, parameters: {
            'orderNo': '',
            'venueFees': '${double.parse('$venueFees').toStringAsFixed(2)}',
            'payType': '${payType}',
            'payResult': '2',
            'desc': '失败原因：您已取消支付'
          });
        } else {
          Get.offNamed(AppRoutes.payResult, parameters: {
            'orderNo': '',
            'venueFees': '${double.parse('$venueFees').toStringAsFixed(2)}',
            'payType': '${payType}',
            'payResult': '2',
            'desc': '支付失败，请稍后再试！'
          });
        }
      });
    } else {
      CustomToast.showTextToast('请先安装支付宝');
    }
  }


}